package ebcs.scan.service.wechat;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;

import ebcs.scan.common.utils.HttpClientUtil;
import ebcs.scan.common.utils.StringUtil;
import ebcs.scan.service.wechat.bean.WechatTemplateList;
import ebcs.scan.service.wechat.bean.WechatTemplateSend;
import ebcs.scan.service.wechat.bean.WechatTemplateSendData;
import jplat.core.session.redis.JRedisConnector;
import jplat.tools.config.JBusConfig;

@Service
public class WeChatTemplPushService {
	 
	private static Logger logger = Logger.getLogger(WeChatTemplPushService.class);
	/**
	 * @描述 发送模版消息
	 * @param touser 推送人的openid
	 * @param url 模板跳转链接
	 * @param data 发送消息内容 
	 * @param tempId 模版顺序id
 	 * @return
	 */
	public String doSendTemplateMsg(String touser,String url,WechatTemplateSendData data,int tempId) {//发送消息
 		String access_token = getRedisToken();//获取当前会话的token  
 
 		String redisTemplateList = getRedisTemplateList();//获取redis缓存的模板列表
		Gson gson = new Gson();
		WechatTemplateList tempList = gson.fromJson(redisTemplateList,WechatTemplateList.class);
 		WechatTemplateSend sendData = new WechatTemplateSend();
 		sendData.setTouser(touser);
 		logger.info("================"+gson.toJson(tempList.getTemplate_list()));
 		sendData.setTemplate_id(tempList.getTemplate_list().get(tempId).getTemplate_id());
 		sendData.setUrl(url);
 		sendData.setData(data);
 		
		String postJson = gson.toJson(sendData);
		logger.info("postdata:===>" + postJson);
		String wechatBackJson =  HttpClientUtil.post(getSendParams(access_token), postJson);
		logger.info("wechatBackJson:" + wechatBackJson);
 		Map tokenGsonMap = gson.fromJson(wechatBackJson, HashMap.class);
		String errmsg = String.valueOf(tokenGsonMap.get("errmsg"));
		logger.info("errmsg:" + errmsg);
		return errmsg;
	}  
	public String doSendTemplateMsg1(String touser,String url,WechatTemplateSendData data,String tempname) {  //发送消息
 		String access_token = getRedisToken();//获取当前会话的token  
 		String redisTemplateList = getRedisTemplateList();//获取redis缓存的模板列表
		Gson gson = new Gson();
		WechatTemplateList tempList = gson.fromJson(redisTemplateList,WechatTemplateList.class);
 		//WechatTemplateList tempList = getTempList(access_token);//1、获取模版列表
 		WechatTemplateSend sendData = new WechatTemplateSend();
 		sendData.setTouser(touser);
 		//Gson gson= new Gson();
 		logger.info("================"+gson.toJson(tempList.getTemplate_list()));
 		logger.info("++++++++++++++++++"+tempList.getTemplate_list().size());
 		for(int i=0;i<tempList.getTemplate_list().size();i++)
 		{
 			logger.info("7777777777777777777777777777777777777:" + tempList.getTemplate_list().get(i).getTitle());
 			if(tempList.getTemplate_list().get(i).getTitle().equals(tempname))
 			{
 				logger.info("7777777777777777777777777777777777777:" + tempList.getTemplate_list().get(i).getTitle());
 				sendData.setTemplate_id(tempList.getTemplate_list().get(i).getTemplate_id());
 			}
 		}
 		//sendData.setTemplate_id(tempList.getTemplate_list().get(tempId).getTemplate_id());
 		sendData.setUrl(url);
 		sendData.setData(data);
		String postJson = gson.toJson(sendData);
		logger.info("postdata:===>" + postJson);
		String wechatBackJson =  HttpClientUtil.post(getSendParams(access_token), postJson);
		logger.info("wechatBackJson:" + wechatBackJson);
 		Map tokenGsonMap = gson.fromJson(wechatBackJson, HashMap.class);
		String errmsg = String.valueOf(tokenGsonMap.get("errmsg"));
		logger.info("errmsg:" + errmsg);
		return errmsg;
	}  
	public String sendWechatMessage(String touser, String url, Map map, String tempId) {
		String access_token = getRedisToken();//获取当前会话的token  
		String redisTemplateList = getRedisTemplateList();//获取redis缓存的模板列表
		Gson gson = new Gson();
		WechatTemplateList tempList = gson.fromJson(redisTemplateList,WechatTemplateList.class);
 		//WechatTemplateList tempList = getTempList(access_token);//1、获取模版列表
 		logger.info("tempList------------------------------:" + tempList.getTemplate_list());
 		Map dataMap = new HashMap();
 		dataMap.put("touser", touser);
 		//Gson gson= new Gson();
 		if(tempList.getTemplate_list() != null) {
 			for(int i=0;i<tempList.getTemplate_list().size();i++)
 	 		{
 	 			if(tempList.getTemplate_list().get(i).getTemplate_id().equals(tempId))
 	 			{
 	 				logger.info("7777777777777777777777777777777777777:" + tempList.getTemplate_list().get(i).getTitle());
 	 				dataMap.put("template_id", tempList.getTemplate_list().get(i).getTemplate_id());
 	 			}
 	 		}
 		}
 		//dataMap.put("template_id", tempId);
 		dataMap.put("url", url);
 		dataMap.put("data", map);
		String postJson = gson.toJson(dataMap);
		logger.info("postdata:===>" + postJson);
		String wechatBackJson =  HttpClientUtil.post(getSendParams(access_token), postJson);
		logger.info("wechatBackJson:" + wechatBackJson);
 		Map tokenGsonMap = gson.fromJson(wechatBackJson, HashMap.class);
		String errmsg = String.valueOf(tokenGsonMap.get("errmsg"));
		logger.info("errmsg:" + errmsg);
		return errmsg;
	}
	/**
	 * 将模板列表存入redis
	 */
	public String getRedisTemplateList() {
		try {    
			 logger.info("getRedisTemplateList++++++++  ");
			 String redisTemplateList = ""; 
			 String access_token = getRedisToken();
			 JRedisConnector redis = JRedisConnector.getInstance();
			 redisTemplateList = redis.get("TEMPLATELIST");
			 if(StringUtil.isEmpty(redisTemplateList)) {
				 redisTemplateList = HttpClientUtil.post(getTemplateList(access_token),"");
				 //redisTemplateList = getTemplateList(access_token);
				 redis.set("TEMPLATELIST", redisTemplateList, 864000);
			 }
			 logger.info("get success redisTemplateList:"+redisTemplateList);
		     return redisTemplateList ;
	    } catch (Exception e) {  
	    	e.printStackTrace();
	    	logger.error("redis error:"+e.getMessage());
	    	return "";
   	    }
	}
		/**
		 * 保存Redis token
		 * @return
		 */
		public String getRedisToken(){
			try {    
			 logger.info("into getToken  ");
			 String access_token = ""; 
			 JRedisConnector redis = JRedisConnector.getInstance();
			  access_token = redis.get("ACCESS_TOKEN");
			  logger.info("get history wechat AccessToken:"+access_token);
		       if(StringUtil.isEmpty(access_token)){
		    		   access_token = getAccess_Token();
			    	   redis.set("ACCESS_TOKEN", access_token, 7000);
		       }else{ 
		    	   access_token = getAccess_Token();
		    	   redis.set("ACCESS_TOKEN", access_token, 7000);
		       } 
				logger.info("get success accessToken:"+access_token);
		       return access_token ;
		    } catch (Exception e) {  
		    	e.printStackTrace();
		    	logger.error("redis error:"+e.getMessage());
		    	return "";
		   	    }
		}
		public WechatTemplateList getTempList(String access_token){
			String wechatBackJson = HttpClientUtil.post(getTemplateList(access_token),"");
 			Gson gson = new Gson();
 			WechatTemplateList tmpList = gson.fromJson(wechatBackJson,WechatTemplateList.class);
			return tmpList;
 		}
	
		public  String getAccess_Token() {//获取accesstoken
			String wechatBackJson = HttpClientUtil.htmlstr(getAccess_TokenParams(
					JBusConfig.WECHAT_APPID,
					JBusConfig.WECHAT_APPSECRET)); 
			Gson gson = new Gson();
			Map tokenGsonMap = gson.fromJson(wechatBackJson, HashMap.class);
			String access_token = String.valueOf(tokenGsonMap.get("access_token"));
			logger.info("access_token:" + access_token);
 			return access_token;
		} 

		public String getAccess_TokenParams(String APPID, String APPSECRET) {//获取accesstoken请求参数
			StringBuilder sb = new StringBuilder();
			sb.append("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential");
			sb.append("&appid=").append(APPID);
			sb.append("&secret=").append(APPSECRET);
			logger.info("getAccess_TokenParams:"+sb.toString());
 			return sb.toString();
		}

		public String getTemplateParams(String access_token) {//获取模板请求参数
			StringBuilder sb = new StringBuilder();
			sb.append("https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token="+access_token);
			return sb.toString();
		}
		public String getTemplate(String template_id_short,String access_token) {//获取模板
			 JSONObject data = new  JSONObject();
			data.put("template_id_short", template_id_short);
			String wechatBackJson = HttpClientUtil.post(getTemplateParams(
					access_token),data.toString());
 			Gson gson = new Gson();
			Map tokenGsonMap = gson.fromJson(wechatBackJson, HashMap.class);
			String template_id = String.valueOf(tokenGsonMap.get("template_id"));
  			return template_id;
		}
		public String getSendParams(String access_token) {//获取发送消息请求参数
			StringBuilder sb = new StringBuilder();
			sb.append("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+access_token);
			logger.info("into getSendParams:"+ sb.toString());
			return sb.toString();
		}
		public String getTemplateList(String access_token) {//获取模版列表
			StringBuilder sb = new StringBuilder();
			sb.append("https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token="+access_token);
			logger.info("into getSendParams:"+ sb.toString());
			return sb.toString();
		}
		public  String getJsapi_Ticket(String access_token) {//获取jsapi_ticket
			String wechatBackJson = HttpClientUtil.htmlstr(getJsapi_TicketParams(
					access_token)); 
			Gson gson = new Gson();
			Map ticketGsonMap = gson.fromJson(wechatBackJson, HashMap.class);
			String ticket = String.valueOf(ticketGsonMap.get("ticket"));
			logger.info("ticket:" + ticket);
 			return ticket;
		}
		public String getJsapi_TicketParams(String access_token) {//获取jsapiTicket请求参数
			StringBuilder sb = new StringBuilder();
			sb.append("https://api.weixin.qq.com/cgi-bin/ticket/getticket");
			sb.append("?access_token=").append(access_token);
			sb.append("&type=jsapi");
			logger.info("getJsapi_TicketParams:"+sb.toString());
 			return sb.toString();
		}
		public  Map<String, String> getWechatConfig(String url){
			WechatSignTools wechatSignTools = new WechatSignTools();
	    	String access_token = getAccess_Token();
			System.out.println("access_token: "+access_token);
			System.out.println("url: "+url);
	        String jsapi_ticket = getJsapi_Ticket(access_token);
	        // 注意 URL 一定要动态获取，不能 hardcode
	        Map<String, String> ret = wechatSignTools.sign(jsapi_ticket, url);
	        logger.info("getWechat_Config:"+ret.toString());
	        return ret;
		}
}
